package NetAPI;

import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerTest {
    public static void main(String[] args) {
        while (true) {
            try {
                Thread.sleep(300);
                Server();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void Server() {
        ServerSocket ss = null;
        Socket socket = null;
        InputStream is = null;
        try {
            // 创建 ServerSocket 对象，绑定端口号
            ss = new ServerSocket(8899);
            // 调用 accept() 方法，接收客户端的请求
            socket = ss.accept();
            // 获取输入流，用于读取数据
            is = socket.getInputStream();
            // 读取数据
            byte[] buffer = new byte[1024];
            int len;
            while ((len = is.read(buffer)) != -1) {
                System.out.println(new String(buffer, 0, len));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (is != null) {
                try {
                    is.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (socket != null) {
                try {
                    socket.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (ss != null) {
                try {
                    ss.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
